const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
const router = require('koa-router')()
router.prefix('/api/user')

router.post('/login', async (ctx, next) => {
  const { userName, userPass } = ctx.request.body;
  if (!userName) {
    ctx.body = new ErrorModel("用户名不能为空")
  }
  if (!userPass) {
    ctx.body = new ErrorModel("密码不能为空")
  }
  const data = await login(userName, userPass)
  if (data) {
    if (data.username) {
      ctx.session.userName = data.username;
    }
    if (data.isadmin) {
      ctx.session.isAdmin = 1;
    }
    ctx.body = new SuccessModel("登录成功");
  } else {
    ctx.body = new ErrorModel("登录失败");
  }
})
router.get('/login-test', (ctx, next) => {
  if (ctx.session.userName) {
    ctx.body = new SuccessModel("登录成功");
  } else {
    ctx.body = new ErrorModel('尚未登录')
  }
})
router.get('/login-out', (ctx, next) => {
  ctx.session.userName = null;
  ctx.session.isAdmin = null;
  ctx.body = new SuccessModel("退出成功");
})

module.exports = router